#include "visionManager.h"
#include "logger.h"
#include "Object.h"
using namespace std;
using namespace cv;
using namespace STRUCT_VISION;



void detectFace( Mat frame );
logger l_vision("vison");
visionManager::visionManager()
{
    //ctor
    m_capture = cvCaptureFromCAM( -1 );
    if(!m_capture)
        m_capture =cvCaptureFromFile("/home/viki/Videos/face.MOV");
    if(!m_capture)
        l_vision.log(ERROR,"visionManager","init capture");
    //cvCaptureFromFile

}

visionManager::~visionManager()
{
    //dtor
}
 string face_cascade_name = "haarcascade_frontalface_alt.xml";

CascadeClassifier face_cascade;
void visionManager::loop()
{

if( !face_cascade.load( face_cascade_name ) ){ printf("--(!)Error loading\n"); return ; };
namedWindow("asd",1);
fa.initData(0,sizeof(FACE_INFO));
    if( m_capture )
   {
     while( true )
     {
        m_frame = cvQueryFrame( m_capture );

   //-- 3. 对当前帧使用分类器进行检测

       if( !m_frame.empty() )
       {
        flip(m_frame,m_frame,-1);
       detectFace( m_frame ); }
       else
       {  break; }

      }
   }
   cout<<"vision done!----------"<<endl;
}

//---------------------------------


// string window_name = "Capture - Face detection";

extern Object fa;

void detectFace( Mat frame )
{
  std::vector<Rect> faces;
  Mat frame_gray;
  FACE_INFO t_face_info;
    t_face_info.p_picture_length=frame.rows;
    t_face_info.p_picture_width=frame.cols;
  cvtColor( frame, frame_gray, CV_BGR2GRAY );
  equalizeHist( frame_gray, frame_gray );
  //-- 多尺寸检测人脸
  face_cascade.detectMultiScale( frame_gray, faces, 1.1, 2, 0|CV_HAAR_SCALE_IMAGE, Size(30, 30) );

  for( int i = 0; i < faces.size(); i++ )
  {
    Point center( faces[i].x + faces[i].width*0.5, faces[i].y + faces[i].height*0.5 );
    t_face_info.p_face_x=center.x;
    t_face_info.p_face_y=center.y;

    ellipse( frame, center, Size( faces[i].width*0.5, faces[i].height*0.5), 0, 0, 360, Scalar( 255, 0, 255 ), 4, 8, 0 );
    fa.writeData(&t_face_info);
  }
   imwrite("t.jpg",frame);

  //-- 显示结果图像
  imshow( "asd", frame );
  waitKey(10);
 }

